package com.example.demo.job;

import com.example.demo.enumclass.NotificationProcessStatusEnum;
import com.example.demo.mq.bo.ScoreMqBo;
import com.example.demo.mq.producer.ScoreMonitorProducer;
import com.example.demo.paymqnotification.entity.PayMqNotificationRecord;
import com.example.demo.paymqnotification.service.IPayMqNotificationRecordService;
import com.example.demo.score.handler.ScoreHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@Component
@Slf4j
@AllArgsConstructor
public class ScoreMonitorJob {

    private ScoreHandler scoreHandler;

    private IPayMqNotificationRecordService iPayMqNotificationRecordService;


    private ScoreMonitorProducer scoreMonitorProducer;

    /**
     * 两分钟检查一次
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    public void checkScoreMonitor() {
        log.info("....执行了通知检查....");
        List<PayMqNotificationRecord> payMqNotificationRecordList = iPayMqNotificationRecordService.lambdaQuery().eq(PayMqNotificationRecord::getStatus, NotificationProcessStatusEnum.Padding.getStatus()).list();
        if (CollectionUtils.isEmpty(payMqNotificationRecordList)) {
            return;
        }
        payMqNotificationRecordList.parallelStream().forEach(it -> {
            scoreHandler.handleScore(ScoreMqBo.buildFromPayMqNotificationRecord(it));
        });
    }

    /**
     * 测试用：
     */
    @Scheduled(fixedRate = 5000)
    public void testProduct() {
        ScoreMqBo scoreMqBo = new ScoreMqBo();
        scoreMqBo.setOrderNo(UUID.randomUUID().toString());
        scoreMqBo.setPrice(new BigDecimal("10"));
        scoreMqBo.setUserId(String.valueOf(System.currentTimeMillis()));
        scoreMqBo.setStatus(NotificationProcessStatusEnum.Padding.getStatus());
        scoreMonitorProducer.sendPayScoreChangeNotification(scoreMqBo);
    }
}
